﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace BatchLogger
{
    static class Logger
    {
        public enum LogType { ERROR, WARNING, INFORM, NONE };
        public static string PathToLogFile { get; set; }

        private static StreamWriter logFile;


        public static void InitializeLogFile(string logFolder, string applicationName, string logTitle)
        {
            PathToLogFile = logFolder;
            string todayString = DateTime.Now.Day.ToString().PadLeft(2, '0') +"_" + DateTime.Now.Month.ToString().PadLeft(2, '0') + "_" + DateTime.Now.Year.ToString();
            string actualTimeString = DateTime.Now.Hour.ToString().PadLeft(2, '0') +"_" + DateTime.Now.Minute.ToString().PadLeft(2, '0');
            string logFileName = string.Concat(PathToLogFile, "\\", applicationName, "_Log__", todayString, "__", actualTimeString, ".html");
            logFile = new StreamWriter(logFileName, false, Encoding.UTF8);
            LogIt(@"<center><b><h1>***** " + logTitle + " *****</h1></b></center>", LogType.NONE);
            LogIt("BATCH STARTED.", Logger.LogType.INFORM);
        }

        public static void LogIt(string message, LogType logType)
        {
            if (logFile != null)
            {
                logFile.Write("<br/>[" + DateTime.Now.ToLongTimeString() + "] ");
                switch (logType)
                {
                    case LogType.ERROR:
                        //Console.WriteLine("\n\nERROR - " + message);
                        logFile.Write("<span style=\"color:red;\"><b>ERROR - </b></span>");
                        break;
                    case LogType.WARNING:
                        //Console.WriteLine("\n\nWARNING - " + message);
                        logFile.Write("<span style=\"color:orange;\"><b>WARNING - </b></span>");
                        break;
                    case LogType.INFORM:
                        //Console.WriteLine("\n\nINFO - " + message);
                        logFile.Write("<span style=\"color:black;\"><b>INFO - </b></span>");
                        break;
                    case LogType.NONE:
                        logFile.Write("<br/>");
                        Console.WriteLine(message);
                        break;
                }
                logFile.WriteLine(message);
                logFile.Flush();
            }
            else
                Console.WriteLine(message);
        }

        public static void LogToFileAndDB(Exception ex, LogType logType, string entryPoint)
        {
            LogIt(ex.ToString(), logType);
            DAL.LogData.SaveLog("BATCH", logType.ToString(), entryPoint, ex.Message, ex.ToString());
        }
    }
}
